package com.example.myretrofit2.httpMesholds;

import com.example.myretrofit2.Car;
import com.example.myretrofit2.UserService2;
import com.example.myretrofit2.common.MyApplication;
import com.example.myretrofit2.httpResult.HttpResult;
import com.example.myretrofit2.service.CarService;
import com.example.myretrofit2.service.CateService;
import com.example.myretrofit2.service.GoodsService;
import com.example.myretrofit2.service.UserService;
import com.example.myretrofit2.unity.RequestInterceptor;
import com.example.myretrofit2.unity.ResponseInterceptor;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class HttpMesholds {
    public static UserService userService;
    public static HttpMesholds mInstance;
    public static CateService cateService;
    public static GoodsService goodsService;
    public static CarService carService;


    public HttpMesholds() {
                      if(mInstance == null) {
                          OkHttpClient client = new OkHttpClient.Builder()
                                  .addInterceptor(new ResponseInterceptor(MyApplication.getContext()))
                                  .addInterceptor(new RequestInterceptor(MyApplication.getContext()))
                                  .build();//声明okhttp
                          Retrofit retrofit = new Retrofit.Builder()
                                  .baseUrl(MyApplication.baseUrl)
                                  .addConverterFactory(GsonConverterFactory.create())
                                  .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                                  .client(client).build();
                          userService = retrofit.create(UserService.class);
                          cateService = retrofit.create(CateService.class);
                          goodsService = retrofit.create(GoodsService.class);
                          carService = retrofit.create(CarService.class);
        }

    }

    public static HttpMesholds getInstance(){
        if(mInstance == null){
            mInstance = new HttpMesholds();
        }
        return mInstance;
    }
    public static class ResultFunc1<T> implements Func1<HttpResult<T>,T>{

        @Override
        public T call(HttpResult<T> tHttpResult) {
           return tHttpResult.getData();
        }
    }
    public static <T> void toSub(Observable<T> o,Subscriber<T> s){
        o.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }
}
